package com.msb.dao.impl;

import com.msb.pojo.Emp;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.beans.BeanProperty;
import java.util.List;

@Repository
public class EmpDaoImpl implements EmpDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int findEmpCount() {
        /*
        * 查询员工个数 queryForObject 有两个参数
        * 1.SQL语句
        * 2.返回值类型
        *
        * */
        Integer empCount = (Integer) jdbcTemplate.queryForObject("select count(1) from emp",Integer.class);
        return empCount;
    }

    @Override
    public Emp findByEmpno(int empno) {
        /*
         * 查询员工个数 queryForObject 有三个参数
         * 1.SQL语句
         * 2.RowMapper  接口的实现类对象，用于执行的结果用哪个类来封装，实现类为BeanPropertyRowMapper
         * 3.SQL语句中需要的参数，可变参数
         * */
        BeanPropertyRowMapper<Emp> rowMapper = new BeanPropertyRowMapper<>(Emp.class);
        Emp emp = jdbcTemplate.queryForObject("select * from emp where empno =?", rowMapper, empno);

        return emp;
    }

    @Override
    public List<Emp> findByDeptno(int deptno) {
        //跟上个函数类似
        List<Emp> empList = jdbcTemplate.query("select * from emp where deptno = ?",new BeanPropertyRowMapper<>(Emp.class),deptno);
        return empList;
    }

    @Override
    public int addEmp(Emp emp) {
        /*
        * 增、删、改、所有操作都使用 update 函数
        * */
        String sql = "insert into emp values (DEFAULT,?,?,?,?,?,?,?)";
        StringBuffer stringBuffer = new StringBuffer(sql);
        StringBuilder stringBuilder = new StringBuilder(sql);
        Object[] args = {emp.getEName(),emp.getEjob(),emp.getMgr(),emp.getHiredate(),emp.getSal(),emp.getComm(),emp.getDeptno(),emp.getEmpno()};
        Integer ret = jdbcTemplate.update(sql,args);
        System.out.println(this.getClass().getName()+ "ret = "+ret);

        return ret;
    }

    @Override
    public int updateEmp(Emp emp) {
        String sql = "update emp set ename = ?,job = ?,mgr = ?,hiredate = ?,sal=?,comm=?,deptno=? where empno = ?";
        Object[] args={emp.getEName(),emp.getEjob(),emp.getMgr(),emp.getHiredate(),emp.getSal(),emp.getComm(),emp.getDeptno(),emp.getEmpno()};
        return jdbcTemplate.update(sql,args);
    }

    @Override
    public int deleteEmp(int empno) {
        String sql = "delete from emp where empno = ?";

        return jdbcTemplate.update(sql,empno);
    }
}
